<template>
    <div class="app-container">
      <el-form label-width="120px" :model="courses" :rules="formRules" ref="dataForm">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courses.name"/>
        </el-form-item>
        <el-form-item label="任课教师" prop="teacherId">
          <el-select v-model="courses.teacherId" filterable clearable placeholder="请选择">
            <el-option
                v-for="tOption in teacherOptions"
                :key="tOption.id"
                :label="tOption.name"
                :value="tOption.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="semesterId">
          <el-select v-model="courses.semesterId" filterable clearable placeholder="请选择">
            <el-option
                v-for="sOption in semesterOptions"
                :key="sOption.id"
                :label="sOption.name"
                :value="sOption.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 课程分类数据 -->
        <el-form-item label="课程分类" prop="subjectsId">
            <el-cascader
                v-model="courses.subjectsId"
                :options="subjectsOptions"
                :props="{ expandTrigger: 'hover',label: 'title',value: 'id', children: 'children' }"
                @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="课程性质" prop="elective">
            <el-select v-model="courses.elective" clearable placeholder="请选择">
            <el-option :value=0 label="选修课"/>
            <el-option :value=1 label="必修课"/>
            </el-select>
        </el-form-item>
        <el-form-item label="备注">
            <el-input
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 5}"
                placeholder="请输入课程备注"
                v-model="courses.comment">
            </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="saveBtnDisabled"
            type="primary"
            @click="saveOrUpdate">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>
  <script>
  import subject from '@/api/cms/subject'
  import courses from '@/api/cms/courses'
  import teacher from '@/api/cms/teacher'
  import semesters from '@/api/cms/semesters'
  export default {
    data() {
      return {
        // 存放班级信息
        courses: {
            name: '',
            teacherId: '',
            subjectsId: '',
            semesterId: '',
            comment: '',
        },
        saveBtnDisabled: false, // 保存按钮是否禁用
        teacherOptions: undefined,
        semesterOptions: undefined,
        subjectsOptions: undefined,
        formRules: {
            name: [
                { required: true, message: '请输入姓名', trigger: 'blur' }
            ],
            teacherId: [
                { required: true, message: '请输入任课教师信息', trigger: 'blur' }
            ],
            semesterId: [
                { required: true, message: '请输入学期信息', trigger: 'blur' }
            ],
            elective: [
                { required: true, message: '请输入课程性质', trigger: 'blur' }
            ]
        }
      }
    },
    watch: {
      $route(to, from) { // 监听路由变化方式
        this.init()
      }
    },
    created() {
      this.init();
      // 获取任课老师数据
      this.getTeacherOption();
      // 获取学期数据
      this.getSemesterOption();
      // 获取课程分类数据
      this.getSubjectOption();
    },
    methods: {
      init() {
        // 判断是否有id
        if (this.$route.params && this.$route.params.id) {
          const id = this.$route.params.id
          this.getInfo(id)
        } else {
            // 做添加 清空表单
            this.courses =  {
                name: '',
                teacherId: '',
                subjectsId: '',
                semesterId: '',
                comment: '',
            }
        }
      },
      // 获取任课老师数据
      getTeacherOption() {
        teacher.findAllTeachers().then(res=>{
          console.log(res)
          this.teacherOptions = res.data.content
        }).catch(err=>{
          console.log(err)
        })
      },
      // 获取学期数据
      getSemesterOption() {
        semesters.findAllSemesters().then(res=>{
          console.log(res)
          this.semesterOptions = res.data.content
        }).catch(err=>{
          console.log(err)
        })
      },
      // 获取课程分类数据
      getSubjectOption() {
        subject.getSubjectList().then(res=>{
          console.log(res)
          this.subjectsOptions = res.data.list
        }).catch(err=>{
          console.log(err)
        })
      },
      handleChange(value) {      
        console.log(value)
        this.courses.subjectsId = value[1];
      },
      // 根据id查询方法
      getInfo(id) {
        console.log("********")
        courses.getInfoById(id)
          .then(response => {
            console.log(response);
            this.courses = response.data.item
          })
      },
      saveOrUpdate() {
        this.$refs.dataForm.validate(valid => {
            // console.log(valid)
            if (valid) {
                // console.log('通过')
            // 表单验证通过，执行提交操作
            this.saveBtnDisabled = true
            // 判断saveBtnDisabled是否有id 修改或添加
                if (!this.courses.id) {
                // 添加
                this.saveData()
                } else {
                this.updateData()
                }
            } else {
            // 表单验证失败，输出错误信息
            // console.log('不通过')
                this.$message.error('请正确输入表单');
            }
        })
      },
      // 修改方法
      updateData() {
        courses.updateInfo(this.courses)
          .then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.$router.push({ path: '/courses/table' })
          }).catch(response => {
            this.$message({
              type: 'error',
              message: '修改失败'
            })
          })
      },
      // 保存
      saveData() {
        courses.addInfo(this.courses)
          .then(response => { // 添加成功
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            // 路由跳转
            this.$router.push({ path: '/courses/table' })
          }).catch(response => {
            this.$message({
              type: 'error',
              message: '保存失败'
            })
          })
      }
    }
  }
  </script>
  